package org.openurp.edu.student.info.web.action

import org.beangle.data.dao.OqlBuilder
import org.beangle.webmvc.api.view.View
import org.beangle.webmvc.entity.action.RestfulAction
import org.openurp.edu.student.info.model.Checkinstate
import org.openurp.edu.student.info.model.Gender
import org.openurp.edu.student.info.model.Stdtype
import org.openurp.edu.student.info.model.Student
import org.openurp.edu.student.info.model.User
import org.openurp.edu.student.info.model.Scholarship
import org.beangle.commons.collection.Order
import org.beangle.commons.lang.ClassLoaders
import org.openurp.edu.student.info.web.helper.ExportExcelUtils
import java.io.OutputStream
import java.{ util => ju }
import org.beangle.data.model.Updated
import org.beangle.webmvc.api.action.ServletSupport
import org.beangle.webmvc.api.annotation.response
import org.beangle.webmvc.api.view.Status
/**
 * @author King Sun
 */
class ManagerCaoAction extends RestfulAction[Student] with ServletSupport {

  override protected def editSetting(entity: Student): Unit = {
    put("genders", entityDao.getAll(classOf[Gender]))
    put("scholarships", entityDao.getAll(classOf[Scholarship]))
    put("stdtypes", entityDao.getAll(classOf[Stdtype]))
    put("checkinstates", entityDao.getAll(classOf[Checkinstate]))
  }

  protected override def getQueryBuilder(): OqlBuilder[Student] = {
    val builder = OqlBuilder.from(classOf[Student], "student")
    populateConditions(builder)
    get("name") foreach { name =>
      builder.where("lower(student.name) like :name", "%" + name.toLowerCase + "%")
    }
    builder.orderBy(get(Order.OrderStr).orNull).limit(getPageLimit)
  }

  def exportexcel(): View = {
    val builder = this.getQueryBuilder()
    builder.limit(null)
    val list = collection.JavaConversions.asJavaCollection(entityDao.search(builder))
    //查出学生信息并放到map中
    val beans = new java.util.HashMap[String, Any]
    beans.put("list", list);
    //获得模板路径
    val path = ClassLoaders.getResourceAsStream("student_information.xls");
    //准备输出流
    var os: OutputStream = null;
    response.setContentType("application/x-excel");
    response.setHeader("Content-Disposition", "attachment;filename=studentInfo.xls");
    os = response.getOutputStream();
    ExportExcelUtils.excprtStudentExcel(beans, path, os);
    Status.Ok
  }

  override protected def saveAndRedirect(student: Student): View = {
    if (student.checkinstate == null) {
      student.checkinstate = new Checkinstate
      student.checkinstate.id = 1L
    }
    student match {
      case updated: Updated => updated.updatedAt = new ju.Date()
      case _ =>
    }
    saveOrUpdate(student)
    redirect("edit", s"&id=${student.id}", "info.save.success")
  }
}